package com.yuelife.controller;

import com.yuelife.entity.CDiscussion;
import com.yuelife.service.CDiscussionService;
import com.yuelife.util.ResultUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * (CDiscussion)表控制层
 *
 * @author makejava
 * @since 2020-06-16 00:37:43
 */
@Api(value = "帖子controller",tags = "帖子controller")
@RestController
@RequestMapping("cDiscussion")
@CrossOrigin
public class CDiscussionController {
    /**
     * 服务对象
     */
    @Resource
    private CDiscussionService cDiscussionService;

    @Autowired
    Environment environment;


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据主键查询",notes = "根据主键id查询,返回一个CDiscussion")
    @ApiImplicitParam(paramType = "query", name = "id", value = "主键id", required = true, dataType = "Integer")
    @GetMapping("selectOne")
    public CDiscussion selectOne(@ApiParam(value = "主键id",name = "id") Integer id) {
        return this.cDiscussionService.queryById(id);
    }

    /**
     * 查询当前社区所有数据
     * @return
     */
    @ApiOperation(value = "根据小区排序查询",notes = "根据小区名字，以及排序规则进行查询，返回一个list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "community",value = "小区名字",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "limit",value = "排序规则,0为最新发帖，1为最后回复",required = true,dataType = "Integer")
    })
    @GetMapping("/selectAllDiscussion")
    @ResponseBody
    public List<CDiscussion> selectAllDiscussion( @RequestParam(value = "community")@ApiParam(value = "小区名字",name = "community") String community,@RequestParam @ApiParam(value = "排序规则",name = "limit")Integer limit){
    return cDiscussionService.selectAll(community,limit);
    }

    /**
     * 添加分享次数数据
    * @Author: yangsen
    * create time: 2020/6/24 11:04
    */
    @ApiOperation(value = "添加分享次数",notes = "根据主键id添加帖子的分享次数,返回ResultUtil")
    @ApiImplicitParam(paramType = "query",name = "id",value = "帖子的主键id",required = true,dataType = "Integer")
    @ApiResponses({@ApiResponse(code = 200, message = "success"),
            @ApiResponse(code = 400, message = "失败 ")})
    @GetMapping("/addshare")
    @ResponseBody
    public ResultUtil addshare(@ApiParam(name = "id",value = "主键id") Integer id){
        try {
            cDiscussionService.addshare(id);
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.faild();
        }
    }

    /**
     * 新发一个帖子
     * @param discussion
     * @return
     */
    @ApiOperation(value = "添加帖子",notes = "新发一个带图片的帖子,需要传入一个CDiscussion对象，一个文件")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "disscussion",value = "一个CDisscusion对象，只需要创建人，标题，内容即可",required = true,dataType = "CDiscussion"),
            @ApiImplicitParam(paramType = "query",name = "file",value = "MultipartFile对象，将上传的图片路径传入即可自动匹配",required = true,dataType = "MultipartFile")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "success"),
            @ApiResponse(code = 400, message = "失败 ")})
    @PostMapping("/creat")
    @ResponseBody
    @Transactional
    public ResultUtil creat(@ApiParam(name = "disscussion",value = "讨论贴对象") CDiscussion discussion,
                            @RequestParam("files") @ApiParam(value = "文件对象",name = "file") MultipartFile file,
                            HttpServletRequest request){
        //获取服务器地址
//        String uploadDir = request.getServletContext().getRealPath("/static/upload/");
        //后缀
        System.out.println("进入到了controlle");
        String fileSuffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        String fileName = (new Date().getTime())+"."+fileSuffix;
        String filePath=environment.getProperty("uploadurl")+fileName;
        discussion.setImg(fileName);
        discussion.setCreateDate(new Date());
        discussion.setLikes(0);
        discussion.setForward(0);
        discussion.setLastReply(new Date());
        discussion.setComments(0);
        try {
            file.transferTo(new File(filePath));
            cDiscussionService.insert(discussion);
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.faild();
        }
//        try {
//            if(cDiscussionService.create(discussion)){
//                return ResultUtil.success();
//            };
//            return ResultUtil.faild();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultUtil.faild();
//        }
    }
    /**
     *
    * @Author: yangsen
    * create time: 2020/6/24 11:12
    */
    @ApiOperation(value = "添加帖子",notes = "新发一个不带图片的帖子,需要传入一个CDiscussion对象")
    @ApiImplicitParam(paramType = "query",name = "disscussion",value = "一个CDisscusion对象，只需要创建人，标题，内容即可",required = true,dataType = "CDiscussion")
    @PostMapping("/creat2")
    @ResponseBody
    @Transactional
    public ResultUtil creat2(@RequestBody @ApiParam(name = "disscusion",value = "一个讨论帖对象") CDiscussion discussion, HttpServletRequest request){

        //获取服务器地址
//        String uploadDir = request.getServletContext().getRealPath("/static/upload/");
        //后缀
        System.out.println(discussion.toString());
        discussion.setCreateDate(new Date());
        discussion.setLikes(0);
        discussion.setForward(0);
        discussion.setLastReply(new Date());
        discussion.setComments(0);
        try {

            cDiscussionService.insert(discussion);
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.faild();
        }
//        try {
//            if(cDiscussionService.create(discussion)){
//                return ResultUtil.success();
//            };
//            return ResultUtil.faild();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultUtil.faild();
//        }
    }

    /**
     * 通过username获取用户所有发过的帖子
    * @Author: yangsen
    * create time: 2020/6/29 11:47
    */
    @GetMapping("/disscussion/{username}")
    @ResponseBody
    public ResultUtil getAllDiscussionByUsername(@PathVariable("username") String username){
        try {
            List<CDiscussion> discussions = cDiscussionService.getAllDiscussionByUsername(username);
            if(discussions!=null){
                Map map = new HashMap<>();
                map.put("discussion",discussions);
                ResultUtil resultUtil = ResultUtil.success();
                resultUtil.setResult(map);
                return resultUtil;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return  ResultUtil.faild();
    }



    /**
     * 向服务器端请求图片的方法，返回byte【】
    * @Author: yangsen
    * create time: 2020/6/24 11:16
    */
    //请求图片的方法
    @ApiOperation(value = "请求图片方法",notes = "根据图片名字，到本地取讨论帖内的图片的方法")
    @GetMapping(value = "/getimg",produces = MediaType.IMAGE_GIF_VALUE)
    @ResponseBody
    public byte[] getimg(String img){
        img = environment.getProperty("uploadurl")+img;
        System.out.println(img);
        File file = new File(img);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);//将文件读取到内存数组中返回
            return b;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}